package com.skynet.amqp.perfect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.time.Instant;

public class MessageSenderImpl implements MessageSender {

    private static final Logger log = LoggerFactory.getLogger(MessageSenderImpl.class);

    @Autowired
    private RetryCache retryCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        retryCache.setSender(this);
    }

    @Override
    public boolean send(String exchange, String routingKey, Object message) {
        return send(new MessageWrapper(retryCache.generateId(), Instant.now().toEpochMilli(), exchange, routingKey, message));
    }

    @Override
    public boolean send(String routingKey, Object message) {
        return send(new MessageWrapper(retryCache.generateId(), Instant.now().toEpochMilli(), "", routingKey, message));
    }

    @Override
    public boolean send(MessageWrapper messageWrapper) {
        try {
            retryCache.add(messageWrapper);
            rabbitTemplate.convertAndSend(messageWrapper.getExchange(), messageWrapper.getRoutingkey(),
                    messageWrapper.getMessage(),
                    new CorrelationData(String.valueOf(messageWrapper.getId())));
        } catch (AmqpException e) {
            log.error("Occur error: {}", e);
            return false;
        }
        return true;
    }
}
